<?php

namespace addons\Employees\merchant\controllers;

use Yii;
use common\traits\Curd;
use common\helpers\ExcelHelper;
use common\models\base\SearchModel;
use common\enums\StatusEnum;
use addons\Employees\common\helpers\ImportHelper;
use addons\Employees\common\models\Employees;
use yii\helpers\Json;

class DefaultController extends BaseController
{
    use Curd;

    public $modelClass = Employees::class;

    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'relations' => [], // 关联 member 表的 nickname 字段
            'partialMatchAttributes' => ['name'], // 模糊查询，注意 member_nickname 为关联表的别名 表名_字段
            'defaultOrder' => [
                'serial' => SORT_ASC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andFilterWhere([$this->modelClass::tableName().'.merchant_id' => $this->getMerchantId()]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,

        ]);
    }

    public function actionAjaxEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);

        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            !empty($model->covers) && $model->covers = Json::encode($model->covers);

            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }

        return $this->renderAjax('ajax-edit', [
            'model' => $model,
        ]);
    }
    public function actionCreate()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);

        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            !empty($model->covers) && $model->covers = Json::encode($model->covers);

            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->render('create', [
            'model' => $model,
        ]);
    }
    public function actionEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);

        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            !empty($model->covers) && $model->covers = Json::encode($model->covers);

            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->render('edit', [
            'model' => $model,
        ]);
    }
    public function actionDelete($id)
    {
        if ($this->findModel($id)->delete()) {
            return $this->message("删除成功", $this->redirect(['index']));
        }
        return $this->message("删除失败", $this->redirect(['index']), 'error');
    }

    /**
     * 导入
     */
    public function actionImport()
    {
        if (Yii::$app->request->isPost) {
            try {
                $file = $_FILES['excelFile'];
                $data = ExcelHelper::import($file['tmp_name'], 2);
                ImportHelper::Employees($data);
            } catch (\Exception $e) {
                return $this->message($e->getMessage(), $this->redirect(['index']), 'error');
            }
            return $this->message('导入成功', $this->redirect(['index']));
        }
        return $this->render('import', [

        ]);
    }
    /**
     * 下载
     */
    public function actionDownload()
    {
        $file = 'employees.xlsx';
        $path = Yii::getAlias('@addons') . '/Employees/common/files/' . $file;
        Yii::$app->response->sendFile($path, Yii::$app->request->get('type').'_' . time() . '.xls');
    }
    /**
     * 导出
     */
    public function actionExport()
    {
        $header = [
            ['员工编号', 'serial'],
            ['姓名', 'name'],
            ['年龄', 'age'],
            ['性别', 'gender', 'selectd', \common\enums\GenderEnum::getMap()],
            ['生日', 'birthday'],
            ['身份证', 'idcard'],
            ['籍贯', 'native'],
            ['政治面貌', 'political', 'selectd', \addons\Employees\common\enums\PoliticalEnum::getMap()],
            ['学历', 'education'],
            ['毕业院校', 'colleges'],
            ['户籍', 'residence'],
            ['手机', 'mobile'],
            ['邮箱', 'mail'],
            ['状态', 'status', 'selectd', [1=>'在职',0=>'离职']],
        ];
        $list = $this->modelClass::find()->select('*')
            ->andWhere(['merchant_id'=>Yii::$app->user->identity->merchant_id])
            ->asArray()
            ->all();
        return ExcelHelper::exportData($list, $header);
    }
    protected function findModel($id)
    {
        if (empty($id) || empty(($model = $this->modelClass::findOne(['id' => $id, 'merchant_id' => $this->getMerchantId()])))) {

            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }

        return $model;
    }
}
